package com.minisoft.jd.normal;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.IOException;

/**
 * @author JueSu
 * @description: TODO
 * @date 2024/4/21 20:16
 */
public class PcOrder {

    private String cookie;
    public static void main(String[] args) throws IOException {
        PcOrder pcOrder = new PcOrder();
        pcOrder.getCookie();
//        pcOrder.checkStock("10103683114817,");
        for (int i = 0; i < 1000; i++) {
            pcOrder.buyNow("10103683114817");
            ThreadUtil.sleep(500);
        }
        //100078536758 芷境2 天青色 40
        //10096620663351 芷境pro 火龙果 44

    }

    /**
     * 对指定的商品进行下单
     */
    public void buyNow(String sku) throws IOException {
//        clearCart();
//        addCart(sku);
        getOrderInfo();
        submitOrder();
    }


    /**
     * 提交订单
     */
    public void submitOrder() throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "body={\"overseaPurchaseCookies\":\"\",\"vendorRemarks\":\"[]\",\"submitOrderParam.sopNotPutInvoice\":\"false\",\"submitOrderParam.trackID\":\"TestTrackId\",\"presaleStockSign\":\"1\",\"submitOrderParam.ignorePriceChange\":\"0\",\"submitOrderParam.btSupport\":\"0\",\"submitOrderParam.eid\":\"jdd03OMIJOWZ3QL6G537C6AMOJEXLTWBG2DLOPREHKBDLDV52NWIWOF54VDTQ5HQM76LS4EHTL4LQS72AT3AD5VBRPN47CIAAAAMPAAD252QAAAAADLOBWEVSAMRE4UX\",\"submitOrderParam.fp\":\"0366757ceda86c4e03af1dd5e284e339\",\"submitOrderParam.jxj\":\"1\",\"submitOrderParam.zpjd\":\"1\",\"submitOrderParam.giftRemove\":\"0\",\"submitOrderParam.limitUserFlag\":\"67776\"}");
        Request request = new Request.Builder()
                .url("https://api.m.jd.com/api?appid=trade-jd-com-v5&loginType=3&client=pc&t=1713692543772&clientVersion=1.0.0&uuid=258787023.16390397454101462430946.1639039745.1713503836.1713692225.82&functionId=pc_trade_submitOrder&cthr=1")
                .method("POST", body)
                .addHeader("accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("cache-control", "no-cache")
                .addHeader("origin", "https://trade.jd.com")
                .addHeader("pragma", "no-cache")
                .addHeader("referer", "https://trade.jd.com/")
                .addHeader("sec-ch-ua", "\"Google Chrome\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "same-site")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .addHeader("Cookie", cookie)
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .addHeader("Host", "api.m.jd.com")
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();
        JSONObject result = JSONUtil.parseObj(response.body().string());
        Console.log("success:{},message:{}", result.get("success"), result.get("message"));
    }

    /**
     * 去结算
     */
    public void getOrderInfo() throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url("https://trade.jd.com/shopping/order/getOrderInfo.action")
                .method("GET", null)
                .addHeader("Host", "trade.jd.com")
                .addHeader("sec-ch-ua", "\"Google Chrome\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("upgrade-insecure-requests", "1")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .addHeader("sec-fetch-site", "same-site")
                .addHeader("sec-fetch-mode", "navigate")
                .addHeader("sec-fetch-user", "?1")
                .addHeader("sec-fetch-dest", "document")
                .addHeader("referer", "https://cart.jd.com/")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", cookie)
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();
        Console.log("success:{},message:{}", response.code(), response.body().string());
    }


    private void getCookie() {
        cookie = FileUtil.readUtf8String("cookies/pcOrder.txt");
    }

    /**
     * 清空购物车
     */
    private void clearCart() throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://api.m.jd.com/api?functionId=pcCart_jc_cartUnCheckAll&appid=JDC_mall_cart&loginType=3&x-api-eid-token=jdd03OMIJOWZ3QL6G537C6AMOJEXLTWBG2DLOPREHKBDLDV52NWIWOF54VDTQ5HQM76LS4EHTL4LQS72AT3AD5VBRPN47CIAAAAMPACZHNAYAAAAACZ6OAWKO3YJBB4X&h5st=20240421204850683;5t5ng9izm63tt6w5;f961a;tk03w79841b3318n8NGXEOue0OKgQFRTF69Mv6hJ2AnlarcoFxImur3B2y6ez09Z438bICkEpKQV8kqUVN0mj0iEMw1v;0125db80401cf230022cdccae99ba5d1;4.1;1713703730683;ee3cf7f6b94dc20e9265d83066bb9ceece4bb89e2b7e8bf5afb1bfd928788174bfa06c210ddd4437d8a2e234330c3a3980b96c3953b1ab788029ae792b39e113b9418ea767c510f79b276449fbd2ced5ec5aa9eba4e48d4eb8f34ddb4aa3ea79f1202ae6fd4561c0cd191574cf49a527994697ccdf6b43a6ea84ea6a2600a7f49c417d43b4235e0a6e540c7ca27fef566575e7312e97e9f6b5b8614df4c409b6c6cd6d92319b0e92c12dc199e5d3a672d7014d6cee8ba71628599d3f4947ad21691daa500a0f251fd47faef4ade86b4a402fed52bdc0a004e6c16f56a68f744264df45cf9df3f3f176feb95abc2932d9566bb4f75d25ea818346f4dc03ee17091ab33a33853a8f23ff256e45efb00f4e589f09b9c6dffd2ddbec04b1b70ab6a4&t=1713703730672&client=pc&clientVersion=1.0.0&body=%7B%22serInfo%22:%7B%22area%22:%2219_1657_3001_0%22,%22user-key%22:%22da9f32b5-7fd5-4b53-921c-5d797c2a2022%22%7D%7D")
                .method("POST", body)
                .addHeader("authority", "api.m.jd.com")
                .addHeader("accept", "application/json, text/plain, */*")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("cache-control", "no-cache")
                .addHeader("origin", "https://cart.jd.com")
                .addHeader("pragma", "no-cache")
                .addHeader("referer", "https://cart.jd.com/")
                .addHeader("sec-ch-ua", "\"Google Chrome\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "same-site")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .addHeader("x-referer-page", "https://cart.jd.com/cart_index")
                .addHeader("x-rp-client", "h5_1.0.0")
                .addHeader("Cookie", cookie)
                .addHeader("Host", "api.m.jd.com")
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();
        Console.log("success:{},message:{}", response.code(), response.body().string());
    }

    /**
     * 加入购物车
     * @param skuId 商品ID
     */

    public boolean addCart(String skuId) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(StrUtil.format("https://cart.jd.com/gate.action?pid={}&pcount=1&ptype=1",skuId))
                .method("GET", null)
                .addHeader("sec-ch-ua", "\"Google Chrome\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("upgrade-insecure-requests", "1")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .addHeader("sec-fetch-site", "same-site")
                .addHeader("sec-fetch-mode", "navigate")
                .addHeader("sec-fetch-user", "?1")
                .addHeader("sec-fetch-dest", "document")
                .addHeader("referer", "https://item.jd.com/")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", cookie)
                .addHeader("Host", "cart.jd.com")
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();
        Console.log("success:{},message:{}", response.code(), response.body().string());
        return true;
    }

    /**
     * 检查库存
     * @param skuIds 商品ID，多个商品ID用英文逗号分隔
     */
    public boolean checkStock(String skuIds) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(StrUtil.format("https://api.m.jd.com/stocks?appid=item-v3&functionId=pc_stocks&client=pc&clientVersion=1.0.0&t=1713695348129&h5st=20240421182908196%3Bzymymzi6j6cq1tu8%3Bfb5df%3Btk03wdd321d1318nRSnl0caCshpAGRrylZVxeR_gLg4sPTN5CbiQf_YhleO0eb6_rjImmeb7VcAldEDfXrO1IPq2Ho_G%3Bf6699f46f8ff29f14626a1319a748bc0%3B4.4%3B1713695348196%3Bbc15aeea977fc5bc2b4f3072713e53bae506e78af453d4c3437fdba2aecb38b26b091907b47c360e2f03e6bcf567ea40fcf4bae0b97852418c5dc7e01a776e53cf65b0aa3a4cdefb8de995bd6bd8e4946ca8f3469b06060d8fbc01cf373beffd5821ff3158d5dc6da6d183a3129b5ec4d7d0a8d260698912190574b59c7be8f101bd9f4412f1a87ec63406ec02c40b04fed51c0377ad6d998dbc2a5455687f1a6a15478fd4e090b2dbf69f4d4372567d41ed54151dbe18a9cf492e44982c81264a5642a41dd91a2b14f9104de1fb5eae81e413ddd7c0c2b6be515ba07d5bba837871cb4f7337594eefb826c7ed0efdec64502192a50cff712ec9deac8a7ca3e1bffdbf5d2e54807000a5fcda63dc55b2cb7dc8dde6718732fb18e28b28455e5b016f1dc2ee70317969e5d13ed600a3afb65384535ee7d1e8bf86842d90427e323f0db5c4b393611674f9be6eb991f9cb&x-api-eid-token=jdd03OMIJOWZ3QL6G537C6AMOJEXLTWBG2DLOPREHKBDLDV52NWIWOF54VDTQ5HQM76LS4EHTL4LQS72AT3AD5VBRPN47CIAAAAMPAAZTMXIAAAAADXAFH53JVHGP7EX&loginType=3&uuid=181111935.16390397454101462430946.1639039745.1713692225.1713695021.83&type=getstocks&skuIds={}&area=19_1657_3001_0", skuIds))
                .method("GET", null)
                .addHeader("authority", "api.m.jd.com")
                .addHeader("accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("cache-control", "no-cache")
                .addHeader("origin", "https://item.jd.com")
                .addHeader("pragma", "no-cache")
                .addHeader("referer", "https://item.jd.com/")
                .addHeader("sec-ch-ua", "\"Google Chrome\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "same-site")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .addHeader("x-referer-page", "https://item.jd.com/100078536770.html")
                .addHeader("x-rp-client", "h5_1.0.0")
                .addHeader("Cookie", cookie)
                .addHeader("Host", "api.m.jd.com")
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        System.out.println("checkStock responseBody: " + responseBody);
        return true;
    }
}
